<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-7-11
 * Time: 16:52
 */

namespace App\Repositories;

use App\Models\Coach;
use App\Models\PlanTemplate;
use App\Models\SchoolConfig;
use Illuminate\Support\Facades\Auth;

class TemplateRepository extends BaseRepository
{
    public $error = '';
    public function __construct(
        PlanTemplate $planTemplate
    )
    {
        $this->model = $planTemplate;
    }


    /**
     * 资源列表
     * @param array $data
     * @param array $extra
     * @param int $size
     * @return mixed
     */
    public function index($data, $extra=[], $size=50)
    {
        $school_id = $data['coach']->school_id;
        $coach = $data['coach'];
        $query =  $this->model->where('school_id', $school_id)->where('coach_id',$coach->id);
        if($data['times']){
            $query->where('type',2)->where('times',$data['times']);
        }else{
            $query->where('type',1);
        }
        $template =  $query->orderBy('orders','asc')->get();
        if(!$template->count() && $data['times']){//数据不存在
            $list = $this->model->where('school_id', $school_id)->where('coach_id',$coach->id)->where('type',1)->get();
            if($list->count())
            {
                foreach ($list as $v){
                    $inputs = [
                        'school_id'=>$v->school_id,
                        'coach_id'=>$v->coach_id,
                        'type'=>2,
                        'km'=>$v->km,
                        'startime'=>$v->startime,
                        'endtime'=>$v->endtime,
                        'minute'=>$v->minute,
                        'max'=>$v->max,
                        'sum_period'=>$v->sum_period,
                        'times'=>$data['times'],
                        'orders'=>$v->orders,
                    ];
                    $this->save(new $this->model,$inputs);
                }
                $template = $list;
            }
        }
        //删除一周前的教练单日模板
        $time=date("Y-m-d",mktime(0,0,0,date("m"),date("d")-7,date("Y")));//一周前时间
        $this->model->where('times','<',strtotime($time))->where('type',2)->delete();
        $school_config = SchoolConfig::where('school_id', $school_id)->first();
        if($school_config){
            $sch_putime_length = $school_config->sch_putime_length;
        }else{
            $sch_putime_length = 0;
        }
        return ['list' => $template, 'sch_putime_length' => $sch_putime_length];
    }

    /**
     * 数据存储
     * @param array $inputs
     * @param string $extra
     * @return mixed
     */
    public function store($inputs = [], $extra = '')
    {
        $model = new $this->model;
        $inputs['school_id'] = $inputs['coach']->school_id;
        if(!$this->verification($inputs)){
            return false;
        }
        return $this->save($model,$inputs);
    }

    public function edit($id, $extra)
    {
        // TODO: Implement edit() method.
    }

    public function update($id, $inputs, $extra='')
    {
        // TODO: Implement update() method.
        $model = $this->getById($id);
        $inputs['school_id'] = $inputs['coach']->school_id;
        if(!$this->verification($inputs)){
            return false;
        }
        return $this->save($model,$inputs);
    }


    /**
     * 获取驾校配置信息
     * @param $school_id
     * @return mixed
     */
    public function getSchoolConfig($school_id)
    {
        return SchoolConfig::where('school_id',$school_id)->first();
    }

    /**
     * 数据删除
     * @param int $id
     * @param string $extra
     * @return mixed
     */
    public function destroy($id = 0, $extra = '')
    {
        return $this->model->where('id',$id)->delete(); // TODO: Change the autogenerated stub
    }

    /**返回教练对应班型模板
     * @param $cid 教练id
     * @param $times 投放学时时间
     * @return array
     */
    public function getCoachTpl($cid, $times=null,$arr=null )
    {
        $query = $this->model->where('school_id',Auth::user()->item_id)->where('coach_id',$cid);
        if($arr){
            if($arr['tfkm']){
                $query->where('km',$arr['tfkm']);
            }
            if($arr['tfms']){
                if($arr['tfms']==1){
                    $query->where('max',1);
                }elseif ($arr['tfms']==2){
                    $query->where('max','>',1);
                }
            }
        }
        if ($times) {
            $query->where('times',$times)->where('type',2);
        }
        $data = $query->get();

        if (!$data->count()) {
            $q =  $this->model->where('school_id',Auth::user()->item_id)->where('coach_id',$cid)->where('type',1);
            if($arr){
                if($arr['tfkm']){
                    $q->where('km',$arr['tfkm']);
                }
                if($arr['tfms']){
                    if($arr['tfms']==1){
                        $q->where('max',1);
                    }elseif ($arr['tfms']==2){
                        $q->where('max','>',1);
                    }
                }
            }
            $data = $q->get();
        }
        return $data;
    }

    /**
     * 赋值其他教练模板
     * @param $data
     * @return bool
     */
    public function copycoachtemplate($data)
    {
        if(count($data['coach_id'])>0){
            $copy_template = self::index(['coach_id'=>$data['copy_id'],'times'=>$data['times']]);

            foreach ($data['coach_id'] as $cid){
                $this->model->where('coach_id',$cid)->where('type',1)->delete();//先删除原默认模板
                foreach ($copy_template as $v){
                    $inputs = [
                        'school_id'=>$v->school_id,
                        'coach_id'=>$cid,
                        'type'=>1,
                        'km'=>$v->km,
                        'startime'=>$v->startime,
                        'endtime'=>$v->endtime,
                        'minute'=>$v->minute,
                        'max'=>$v->max,
                        'sum_period'=>$v->sum_period,
                        'times'=>0,
                        'orders'=>$v->orders,
                    ];
                    $this->save(new $this->model,$inputs);
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 调用教练模板 模板资源
     * @param $data
     * @return mixed
     */
    public function othertemplate($data)
    {
        $template = $this->model->where('school_id',Auth::user()->item_id)->where('type',1)->where('coach_id','<>',$data['coach_id'])->select('id','coach_id')->groupBy('coach_id')->get();
        if($template->count()){
            foreach ($template as $value){
                $coach = Coach::where('id',$value->coach_id)->select('id','name')->first();
                $value->name = $coach->name;
            }
        }
        return $template;
    }

    /**
     * 调用其他教练模板
     * @param $data
     */
    public function copytemplate($data)
    {
        $template = self::index(['coach_id'=>$data['copy_id'],'times'=>0]);
        if(!$template->count()){
            return false;
        }
        $type = $data['times']?2:1;
        $times = $data['times']?$data['times']:0;
        if($type == 1){
            $this->model->where('coach_id',$data['coach_id'])->where('type',1)->delete();
        }elseif($type == 2){
            $this->model->where('coach_id',$data['coach_id'])->where('type',2)->where('times',$times)->delete();
        }
        foreach ($template as $v){
            $inputs = [
                'school_id'=>$v->school_id,
                'coach_id'=>$data['coach_id'],
                'type'=>$type,
                'km'=>$v->km,
                'startime'=>$v->startime,
                'endtime'=>$v->endtime,
                'minute'=>$v->minute,
                'max'=>$v->max,
                'sum_period'=>$v->sum_period,
                'times'=>$times,
                'orders'=>$v->orders,
            ];
            $this->save(new $this->model,$inputs);
        }
        return true;
    }
    /**
     * 数据入库
     * @param $model
     * @param $inputs
     * @return mixed
     */
    public function save($model , $inputs)
    {
        if (array_key_exists('school_id',$inputs)) {
            $model->school_id = e($inputs['school_id']);//驾校id
        }
        if (array_key_exists('coach_id',$inputs)) {
            $model->coach_id = e(trim($inputs['coach_id']));//教练id
        }
        if (array_key_exists('type',$inputs)) {
            $model->type = e($inputs['type']);//模板类型    1：教练默认模板   2：教练个人单日模
        }
        if (array_key_exists('km',$inputs)) {
            $model->km = e($inputs['km']);//学习科目
        }
        if (array_key_exists('startime',$inputs)) {
            $model->startime = e($inputs['startime']);//开始时间
        }
        if (array_key_exists('endtime',$inputs)) {
            $model->endtime = e($inputs['endtime']);//结束时间
        }
        if (array_key_exists('minute',$inputs)) {
            $model->minute = e($inputs['minute']);//时长 分钟数
        }
        if (array_key_exists('max',$inputs)) {
            $model->max = e($inputs['max']);//最大预约人数
        }
        if (array_key_exists('sum_period',$inputs)) {
            $model->sum_period = e($inputs['sum_period']);//总学时
        }
        if (array_key_exists('times',$inputs)) {
            $model->times = e($inputs['times']);//模板生效时间
        }
        $model->orders = strtotime('2017-01-01 '.e($inputs['startime']));//排序
        if($model->save()){

            return $model;
        }
        return false;
    }

    /**
     * 排班数据验证
     * @param $data
     * @return bool
     */
    public function verification($data)
    {
        $sch_config = self::getSchoolConfig($data['school_id']);//权限配置

        if($data['max']==0){
            $this->error = '提示:学车人数不能为0';
            return false;
        }
        if (strtotime($data['startime']) >= strtotime($data['endtime']) ) {
            $this->error = '提示:结束时间必须大于开始时间';
            return false;
        }elseif((strtotime($data['endtime'])-strtotime($data['startime']))< ($sch_config->sch_putime_length*60)){
            $this->error = '提示:单个学时时间必须大于'.$sch_config->sch_putime_length.'分钟';
            return false;
        }elseif (strtotime($data['startime'])< strtotime(date('Y-m-d 6:00:00',time()))){
            $this->error = '提示:学时开始时间不能小于6点';
            return false;
        }
        $startime = strtotime($data['startime']) - ($sch_config->sch_putime_interval*60); //新增时段 开始时间转换成时间戳
        $endtime = strtotime($data['endtime']) + ($sch_config->sch_putime_interval*60);//新增时段 结束时间转换成时间戳
        if($data['type']==1){//教练默认模板验证
            $list = $this->model->where('school_id',$data['school_id'])->where('coach_id',$data['coach_id'])->where('type',1)->get();
            //判断时间段是否冲突
            foreach ($list as $k=>$v ) { //比对冲突
                $mb_startime = strtotime($v->startime);
                $mb_endtime = strtotime($v->endtime);
                if(isset($data['id'])){
                    if($data['id']==$v->id) continue;
                }
                if ( ($mb_startime > $startime && $mb_startime<$endtime) || ($mb_endtime > $startime && $mb_endtime<$endtime) || ($mb_startime <=$startime &&  $mb_endtime>= $endtime)) {
                    $this->error = '提示:时间段之间有冲突，请先处理!';
                    return false;
                }
            }

        }else{//教练单日模板验证

            $list = $this->model->where('school_id',$data['school_id'])->where('coach_id',$data['coach_id'])->where('type',2)->where('times',$data['times'])->get();
            //判断时间段是否冲突
            foreach ($list as $k=>$v ) { //比对冲突
                $mb_startime = strtotime($v->startime);
                $mb_endtime = strtotime($v->endtime);
                if(isset($data['id'])){
                    if($data['id']==$v->id) continue;
                }
                if ( ($mb_startime > $startime && $mb_startime<$endtime) || ($mb_endtime > $startime && $mb_endtime<$endtime) || ($mb_startime <=$startime &&  $mb_endtime>= $endtime)) {
                    $this->error = '提示:时间段之间有冲突，请先处理!';
                    return false;
                }
            }

        }

        return true;
    }


    /**
     * 将教练的的单日模板设为默认模板
     * @param $coach_info
     * @param $date
     */
    public function templateSaveDefault($coach_info, $date)
    {
        $template_info = $this->model->where('coach_id', $coach_info->id)->where('type', 2)->where('times', strtotime($date))->get();

        if(!$template_info->count()){
            return ['state' => false, 'msg' => '不存在的当日模板'];
        }

        $this->model->where('coach_id', $coach_info->id)->where('type', 1)->delete();
        foreach($template_info as $template){
            $inputs = [
                'school_id'=>$template->school_id,
                'coach_id'=>$template->coach_id,
                'type'=>1,
                'km'=>$template->km,
                'startime'=>$template->startime,
                'endtime'=>$template->endtime,
                'minute'=>$template->minute,
                'max'=>$template->max,
                'sum_period'=>$template->sum_period,
                'times'=>0,
                'orders'=>$template->orders,
            ];
            $this->save(new $this->model,$inputs);
        }

        return ['state' => true];
    }
}